<script setup lang="ts">
  import { ref, watch, computed, reactive } from 'vue';
  import { useBooleanStore } from '@/store';
  import {
    ERPLogDelete,
    ERPLogSend,
    ERPLogChanged,
  } from '@/api/operation-monitoring';
  import { Notification } from '@arco-design/web-vue';

  const emit = defineEmits(['resendSearch', 'sendMsgid']);
  const props = defineProps<{
    tableData: any;
  }>();
  const columns: any[] = [
    {
      title: '序号',
      dataIndex: 'PAGEHELPER_ROW_ID',
      key: 'PAGEHELPER_ROW_ID',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '传输标识',
      dataIndex: 'msgId',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '类型',
      dataIndex: 'issuedType',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '交接单号',
      dataIndex: 'deliveryPlanCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '图号',
      dataIndex: 'itemCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '型号',
      dataIndex: 'mProductNumber',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '质量编号',
      dataIndex: 'qualityCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '条码号',
      dataIndex: 'barcode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '传递ERP参数',
      dataIndex: 'bData',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '发起时间',
      dataIndex: 'issuedTime',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '调用结果编码',
      dataIndex: 'retCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '调用结果',
      dataIndex: 'result',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
  ];
  const booleanStore = useBooleanStore();
  // 创建一个响应式的本地副本
  const localTableData = ref<any>();
  // 数据库一共有多少条
  const total = ref<number>(1);
  const pageNum = ref<number>(1);
  const pageSize = ref<number>(10);
  const visibleDelete = ref<boolean>(false);
  const visibleSend = ref<boolean>(false);
  const visibleChange = ref<boolean>(false);
  const selectedKeys = ref<string[]>();
  // 计算已选择的表格数据
  const selectedTableData = computed(() => {
    if (selectedKeys.value && localTableData.value) {
      return localTableData.value.filter((item: any) =>
        selectedKeys.value?.includes(item.PAGEHELPER_ROW_ID)
      );
    }
    return null;
  });
  const rowSelection = reactive({
    type: 'checkbox' as 'checkbox' | 'radio',
    showCheckedAll: true,
  });
  const form = reactive({
    msgId: '',
    bData: '',
    PAGEHELPER_ROW_ID: '',
    issuedId: '',
    issuedTime: '',
    issuedType: '',
    result: '',
    retCode: '',
  });
  function handleCancel() {
    visibleChange.value = false;
    visibleSend.value = false;
    visibleDelete.value = false;
  }
  async function changedOk() {
    const response = await ERPLogChanged(form);
    if (response.retCode === '200') {
      selectedKeys.value = [];
      Notification.success({
        title: '成功',
        content: response.message,
        closable: true,
      });
      emit('resendSearch');
    } else {
      Notification.error({
        title: '失败',
        content: response.message,
        closable: true,
      });
    }
  }
  async function deleteOk() {
    const response = await ERPLogDelete(selectedTableData.value);
    if (response.retCode === '200') {
      selectedKeys.value = [];
      Notification.success({
        title: '成功',
        content: response.message,
        closable: true,
      });
      emit('resendSearch');
    } else {
      Notification.error({
        title: '失败',
        content: response.message,
        closable: true,
      });
    }
  }
  async function sendOk() {
    const response = await ERPLogSend(selectedTableData.value);
    if (response.retCode === '200') {
      selectedKeys.value = [];
      Notification.success({
        title: '成功',
        content: response.message,
        closable: true,
      });
      emit('resendSearch');
    } else {
      Notification.error({
        title: '失败',
        content: response.message,
        closable: true,
      });
    }
  }
  function erpClick(item: number) {
    if (selectedKeys.value?.length === 0) {
      Notification.error({
        title: '提示',
        content: '请选择至少一条数据',
        closable: true,
      });
    }
    if (item === 1) {
      if (selectedKeys.value?.length === 1) {
        form.msgId = selectedTableData.value[0].msgId;
        form.bData = selectedTableData.value[0].bData;
        form.PAGEHELPER_ROW_ID = selectedTableData.value[0].PAGEHELPER_ROW_ID;
        form.issuedId = selectedTableData.value[0].issuedId;
        form.issuedTime = selectedTableData.value[0].issuedTime;
        form.issuedType = selectedTableData.value[0].issuedType;
        form.result = selectedTableData.value[0].result;
        form.retCode = selectedTableData.value[0].retCode;
        visibleChange.value = true;
      } else {
        Notification.error({
          title: '提示',
          content: '若要修改数据,请只选择一条数据',
          closable: true,
        });
      }
    }
    if (item === 2) {
      visibleDelete.value = true;
    }
    if (item === 3) {
      visibleSend.value = true;
    }
  }
  function tableClick(record: any) {
    emit('sendMsgid', record.msgId);
  }
  // 监听props.tableData的变化，并更新本地副本
  watch(
    () => props.tableData,
    () => {
      localTableData.value = props.tableData?.list;
      total.value = props.tableData?.total || 1;
    },
    { immediate: true }
  );
  // 监听页面变化
  watch([pageNum, pageSize], () => {
    booleanStore.setPage(pageNum.value, pageSize.value, 38);
  });
  // 监听已选择数据的序号，并更新到已选择表格数据行字段
  function change(e: any) {
    pageNum.value = e;
  }
  function changeSize(e: any) {
    pageSize.value = e;
  }
</script>

<template>
  <a-space>
    <a-button type="outline" @click="erpClick(1)">修改数据</a-button>
    <a-button type="outline" @click="erpClick(2)">删除数据</a-button>
    <a-button type="outline" @click="erpClick(3)">推送数据</a-button>
  </a-space>
  <div style="margin-top: 8px">
    <a-table
      v-model:selected-keys="selectedKeys"
      :stripe="true"
      class="top-table"
      :pagination="false"
      :columns="columns"
      :data="localTableData"
      :row-selection="rowSelection"
      row-key="PAGEHELPER_ROW_ID"
      @row-click="tableClick"
    >
    </a-table>
    <div class="page-position">
      <a-pagination
        :total="total"
        :current="pageNum"
        :page-size="pageSize"
        show-total
        show-jumper
        show-page-size
        @update:page-size="changeSize"
        @change="change"
      />
    </div>
  </div>
  <a-modal
    v-model:visible="visibleChange"
    width="800px"
    height="800px"
    @ok="changedOk"
    @cancel="handleCancel"
  >
    <template #title> erp日志修改 </template>
    <div class="content">
      <a-form :model="form">
        <a-form-item field="msgId" label="消息ID">
          <a-input v-model="form.msgId"></a-input>
        </a-form-item>
        <a-form-item field="bData" label="参数内容">
          <a-mention
            v-model="form.bData"
            type="textarea"
            style="height: 180px"
          ></a-mention>
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
  <a-modal
    v-model:visible="visibleDelete"
    @ok="deleteOk"
    @cancel="handleCancel"
  >
    <template #title> 警告 </template>
    <div class="modal-content"
      >当前已选择{{
        selectedKeys?.length
      }}条数据,确定要删除已选择的数据吗？</div
    >
  </a-modal>
  <a-modal v-model:visible="visibleSend" @ok="sendOk" @cancel="handleCancel">
    <template #title> 警告 </template>
    <div class="modal-content"
      >当前已选择{{
        selectedKeys?.length
      }}条数据,确定要推送已选择的数据吗？</div
    >
  </a-modal>
</template>

<style scoped>
  .top-table {
    white-space: nowrap;
  }
  .page-position {
    margin-top: 20px;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .content {
    display: flex;
    flex-direction: column;
  }
  .modal-content {
    font-size: large;
  }
</style>
